package com.freework.report.base.service.filterCondition;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.freework.report.base.service.filterCondition.Condition.Location;
import com.freework.util.NumberUtil;



public class  BuilderFilterConditionSQL {

	List<Object> values = null;
	FilterConditionItemSQLFactory factory=new FilterConditionItemSQLFactory();

    public    void builderSQL(StringBuilder sql, Condition condition,String byTableName,String value){
    	FilterConditionItemSQL itme=factory.filterConditionItemSQL(condition.getSQLtype());
    	condition.setPrepare(itme.isPrepare());
    	sql.append(itme.getSQL(condition, byTableName, value));
    }
    
	

	public  String getSQL(boolean isFirst, Map values, Condition items[],
			String byTableName) {
		if(values==null)
			return "";
		StringBuilder sql = new StringBuilder(items.length * 8);
		String value = null;
		this.values = new ArrayList<Object>();
		for (Condition item : items) {
			value = (String) values.get(item.getParamName());

			if (value != null && !value.equals("")) {
				if (isFirst){
					isFirst = false;
					sql.append(" where ");
				}else
					sql.append(item.getRelation());
				builderSQL(sql,item,byTableName,value);
				if (item.isPrepare()) {
					this.values.add(prepareValue(item.isNumber(),value,item.getLikeLocation()));
				}
			}

		}
		return sql.toString();

	}

	
	public Object prepareValue(boolean isNumber,String value,Location likeLocation){
		if(likeLocation==null)
			return isNumber ? value : NumberUtil.bigDecimal(value);
		else{
			switch (likeLocation){
    		case all:
    			return "%"+value+"%";
    		case  left:
    			return "%"+value;
    		case  right:
    			return value+"%";
    			
    		}
    		
			return "%"+value+"%";

		}
		
	}
	
	public void setPrepareStatement(int i, PreparedStatement prpe)
			throws SQLException {
		if(values==null)
			return ;
		for (Object value : values) {
			if (value.getClass() == String.class)
				prpe.setString(i, (String) value);
			else if (value.getClass() == BigDecimal.class)
				prpe.setBigDecimal(i, (BigDecimal) value);
			else
				prpe.setObject(i, value);
			i++;
		}
	}

}
